// 云函数入口文件
const cloud = require('wx-server-sdk')
// const Parser = require('rss-parser');
// const md5 = require('md5');
// let parser = new Parser();


cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  // const wxContext = cloud.getWXContext()
  const db = cloud.database({
    // env: 'dev-d62e0'
  })
  let result = {}

  const {
    rssUrl,
    current =1
  } = event
  // let id = md5(rssUrl)

  let rss = await db.collection('rss_item').where({
    siteUrl: rssUrl
  }).field({
    img: true,
    link: true,
    title: true,
    pubDate: true,
  }).limit(10).skip((current-1)*10).get()
  if (rss.data.length == 0) {
    let res = await cloud.callFunction({
      name: 'syncRss',
      data: {
        rssUrl
      },
      config: {
        // env: 'dev-d62e0'
      }
    })

    let rss = await db.collection('rss_item').where({
      siteUrl: rssUrl
    }).field({
      img: true,
      link: true,
      title: true,
      pubDate: true,
    }).limit(10).get()
    result.list = rss.data
   
  } else {
    // cloud.callFunction({
    //   name: 'syncRss',
    //   data: {
    //     rssUrl
    //   },
    //   config: {
    //     env: 'dev-d62e0'
    //   }
    // }).catch(()=>{
    //   console.log('同步失败')
    // }).then(res=>{
    //   console.log('同步完成')
    // })

    result.list = rss.data
  }
  await db.collection('rss_subscribe').where({
    url: rssUrl
  }).update({
    data: {
      pullTime: new Date()
    }
  })
  const count = await db.collection('rss_item').where({
    siteUrl: rssUrl
  }).count()
  result.total = count.total
  console.log('result=', result)
  return result;
  let json = await parser.parseURL(rssUrl)
  //  await db.collection('rss_item').update.add({
  //    data:{
  //      title:"dasd"
  //    }
  //  })
  // const {
  //   items
  // } = json
  // for (let i = 0; i < items.length; i++) {
  //   await db.collection('rss_item').doc(items[i].link+'').set({
  //     data: items[i]
  //   })
    
  
  // }
  // items.forEach(item => {
  //   all.push(db.collection('rss_item').doc('link').set({
  //     data: {
  //       link:item.link
  //     }
  //   }))
  // })
  // await Promise.all(all)
console.log('json=',json)
  return json;
}